<template>
  <view class="hb-w-[622rpx]">
    <view
      class="message-bubble hb-flex hb-gap-3 hb-items-center hb-inline-block hb-rounded-lg hb-p-3 hb-bg-[#FFF] hb-box-shadow-base"
      style="width: fit-content; max-width: 100%; word-break: break-all"
    >
      <view v-if="data.loading" class="hb-flex hb-items-center hb-gap-2">
        <tm-spin :size="28" :load="true" icon="ali-icon icon-jiazai hb-mt-2" />
        <view class="hb-text-sm hb-text-gray-500">{{ data.content }}</view>
      </view>
      <view class="hb-flex-1" v-else>
        <TextMessage :message="data.content" :message-index="index" />
      </view>
    </view>
    <view
      v-if="data?.content && jsonCard(data.content)?.length"
      :class="[' hb-mt-3 hb-flex hb-flex-col hb-gap-3 ', 'animate-fade-in']"
    >
      <ConnectionsInfo
        v-for="(item, index) in jsonCard(data.content)"
        :key="index"
        :connection-info="item"
      ></ConnectionsInfo>
    </view>

    <view v-if="!data.typing && !data.loading" :class="['animate-fade-in']">
      <MessageTool
        :refreshable="isLast"
        :content="data.content"
        @resend="handleResend"
        @copy="handleCopy"
      ></MessageTool>
    </view>

    <view
      v-if="!data.typing && !data.loading && jsonQuick(data.content).length > 0 && isLast"
      :class="['quick-reply-list', 'animate-fade-in']"
    >
      <QuickReplyList :replies="jsonQuick(data.content)" @send="handleMessageSend"></QuickReplyList>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import TextMessage from './TextMessage.vue';
  import { ConnectionInfo, MessageRecord } from '@/api/aiChatPage/types';
  import ConnectionsInfo from './ConnectionsInfo.vue';
  import QuickReplyList from './QuickReplyList.vue';
  import MessageTool from './MessageTool.vue';
  const props = defineProps<{
    data: MessageRecord;
    index: number;
    isLast: boolean;
  }>();

  const emit = defineEmits<{
    (e: 'resend'): void;
    (e: 'send', reply: string): void;
  }>();

  const removeBrTags = (str: string): string => {
    return str.replace(/<br\s*\/?>/gi, '');
  };

  const jsonCard = (content: string) => {
    const matches = content.matchAll(/<json-card>([\s\S]*?)<\/json-card>/g);

    if (!matches) return [];

    const result: ConnectionInfo[] = [];

    for (const match of matches) {
      const jsonStr = match[1];
      if (jsonStr) {
        try {
          const cleanJsonStr = removeBrTags(jsonStr);
          result.push(JSON.parse(cleanJsonStr) as ConnectionInfo);
        } catch (e) {
          console.error('解析json-card失败', e);
        }
      }
    }
    return result;
  };

  const jsonQuick = (content: string) => {
    const jsonStr = content.match(/<json-quick>([\s\S]*?)<\/json-quick>/)?.at(1);
    if (!jsonStr) return [];

    try {
      const parsed = JSON.parse(jsonStr);
      // 确保结果是数组
      if (Array.isArray(parsed)) {
        return parsed as string[];
      } else {
        return [];
      }
    } catch (e) {
      console.error('解析json-quick失败', e);
      return [];
    }
  };
  const handleResend = () => {
    emit('resend');
  };
  const handleCopy = () => {
    uni.setClipboardData({
      data: props.data.content,
      success: () => {
        uni.showToast({
          title: '已复制',
          icon: 'none',
        });
      },
    });
  };
  const handleMessageSend = (reply: string) => {
    emit('send', reply);
  };
</script>

<style lang="scss" scoped>
  .message-bubble {
    position: relative;
    &::after {
      content: '';
      position: absolute;
      left: -10rpx;
      top: 30%;
      transform: translateY(-30%);
      border-right: 12rpx solid #fff;
      border-top: 12rpx solid transparent;
      border-bottom: 12rpx solid transparent;
    }
  }

  /* uniapp 动画类 */
  .animate-fade-in {
    animation: fadeIn 0.3s ease forwards;
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }
</style>
